<template>
  <div class="login-container">
    <div class="login-border animated fadeInRight">
      <a-form-model :model="formInline" ref="ruleForm" :rules="rules">
        <h4 class="login-title">欢迎登录Miss记账后台</h4>
        <a-form-model-item prop="username">
          <a-input v-model="formInline.username" placeholder="用户名" allow-clear>
            <a-icon slot="prefix" type="user" style="color:rgba(0,0,0,.25)" />
          </a-input>
        </a-form-model-item>
        <a-form-model-item prop="password">
          <a-input-password v-model="formInline.password" placeholder="密码" allow-clear>
            <a-icon slot="prefix" type="lock" style="color:rgba(0,0,0,.25)" />
          </a-input-password>
        </a-form-model-item>
        <a-row :gutter="10">
          <a-col :span="16">
            <a-form-model-item :has-feedback="validateCode" prop="code" validate-status="success">
              <a-input id="validating" v-model="formInline.code" placeholder="验证码">
                <a-icon slot="prefix" type="code" style="color:rgba(0,0,0,.25)" />
              </a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <div class="captcha">
              <input type="button" class="verification" v-model="checkCode" @click="createCode" />
            </div>
          </a-col>
        </a-row>
        <a-form-model-item>
          <a-button
            type="primary"
            class="login-btn"
            shape="round"
            :loading="loading"
            @click="handleSubmit"
          >
            登录
          </a-button>
        </a-form-model-item>
      </a-form-model>
    </div>
  </div>
</template>

<script>
export default {
  name: "Login",
  data() {
    return {
      formInline: {
        username: '',
        password: '',
        code: ''
      },
      validateCode: false,
      checkCode: '',
      loading: false,
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '密码长度6~15位', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { validator: this.handleCheckCode, trigger: "blur" },
        ],
      }
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  mounted() {
    this.createCode()
  },
  methods: {
    handleCheckCode(rule, value, callback) {
      this.validateCode = false
      if (value == "") {
        callback(new Error("验证码不能为空"));
      } else {
        if (value != this.checkCode) {
          callback(new Error("验证码错误"));
        } else {
          callback();
          this.validateCode = true
        }
      }
    },
    handleSubmit() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (this.loading) return; // 防止重复点击登录
          this.loading = true;
          // 登录
          try {
            await this.$store.dispatch("user/login", this.formInline)
            this.loading = false;
            this.$message.success("登录成功");
            window.location.href = "/"
          } catch (error) {
            console.log('error', error);
            this.loading = false;
            this.$message.error(error.message || "验证错误， 请重新登录");
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    createCode() {
      this.$refs.ruleForm.clearValidate('code');
      this.formInline.code = "";
      this.checkCode = "";
      let code = "";
      //验证码的长度
      const codeLength = 4;
      //随机数
      const random = [0,1,2,3,4,5,6,7,8,9];
      for (let i = 0; i < codeLength; i++) {
        //取得随机数的索引（0~35）
        let index = Math.floor(Math.random() * 10);
        //根据索引取得随机数加到code上
        code += random[index];
      }
      //把code值赋给验证码
      this.checkCode = code;
    },
  },
};
</script>

<style lang="less" scoped>

.login-container {
  height: 100vh;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  -ms-flex-pack: distribute;
  justify-content: space-around;
  background: rgba(0,0,0,.2);
  position: relative;
}
.login-container:before {
  z-index: -999;
  content: "";
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-image: url(https://zht-test.zhonghuilv.net/img/login.e3347162.png);
  background-size: cover;
}
.login-border {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -ms-flex-direction: column;
  flex-direction: column;
  padding: 30px 50px 25px 50px;
  background-color: #fff;
  border-radius: 6px;
  -webkit-box-shadow: 1px 1px 2px #eee;
  box-shadow: 1px 1px 2px #eee;
  margin-left: 50%;
  width: 330px;
}
.login-btn {
  width: 100%;
}
.login-title {
  margin: 0 0 20px;
  text-align: center;
  color: #409eff;
  letter-spacing: 3px;
}
.captcha {
  display: flex;
  align-items: center;
  line-height: 40px;
  height: 40px;
  .verification {
    cursor: pointer;
    height: 32px;
    background-color: #fdfdfd;
    border: 1px solid #f0f0f0;
    color: #333;
    font-size: 14px;
    font-weight: 700;
    letter-spacing: 5px;
    text-indent: 5px;
    text-align: center;
  }
}
</style>
